class VastApi
  class Attributes < Hash
    attr_reader :response, :xml, :url, :vast

    def listings
      @listings ||= vast.listings
    end

    def initialize(vast)
      @vast = vast
      @url = "#{@vast.api_url}attributes/-/#{@vast.category}?#{@vast.query}"
      @response = Typhoeus::Request.get(@url)
      @xml = Nokogiri::XML(@response.body)
      populate
    end

    def attr(var_name)
      if var = @xml.at(var_name)
        var.text
      elsif var = @xml.at('//v:'+var_name)
        var.text
      elsif var = @xml.at('//o:'+var_name)
        var.text
      else
        nil
      end
    end

  private

    def populate
      @xml.css("entry").each do |entry|
        e = @vast.create_entry(entry)
        if e.kind_of? VastApi::Listings::Entry
          @listings ||= []
          @listings << e
        elsif e.kind_of? VastApi::Attributes::Entry
          self[entry.at_xpath('v:attribute')['id']] = e
        end
      end
    end
  end
end
